package com.chenailin.www.controller.knowledge;

import com.chenailin.www.model.dto.KnowledgeBaseDTO;
import com.chenailin.www.model.pojo.KnowledgeBase;
import com.chenailin.www.model.vo.KnowledgeBaseVO;
import com.chenailin.www.model.vo.ResultVO;
import com.chenailin.www.service.KnowledgeService;
import com.chenailin.www.serviceimpl.KnowledgeServiceImpl;
import com.chenailin.www.util.JsonUtil;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author evi
 */
@WebServlet("/knowledge/*")
public class KnowledgeBaseController extends HttpServlet {
    private final KnowledgeService knowledgeService = new KnowledgeServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getRequestURI().substring(req.getContextPath().length());
        Long userId = (Long) req.getSession().getAttribute("userId");

        try {
            if (path.startsWith("/knowledge/list/my")) {
                List<KnowledgeBaseVO> list = knowledgeService.listUserBases(userId);
                resp.getWriter().write(JsonUtil.toJson(ResultVO.success(list)));
            } else if (path.startsWith("/knowledge/list/public")) {
                List<KnowledgeBaseVO> list = knowledgeService.listPublicBases();
                resp.getWriter().write(JsonUtil.toJson(ResultVO.success(list)));
            } else if (path.startsWith("/knowledge/")) {
// ！！！
                Long id = Long.parseLong(path.substring("/knowledge/".length()));
                KnowledgeBaseVO vo = knowledgeService.getBaseById(id, userId);
                resp.getWriter().write(JsonUtil.toJson(ResultVO.success(vo)));
            }
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write(JsonUtil.toJson(ResultVO.error(400, e.getMessage())));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Long userId = (Long) req.getSession().getAttribute("userId");
        KnowledgeBaseDTO dto = JsonUtil.fromJson(IOUtils.toString(req.getReader()), KnowledgeBaseDTO.class);

        try {
            KnowledgeBase base = knowledgeService.createBase(dto, userId);
            resp.getWriter().write(JsonUtil.toJson(ResultVO.success(base)));
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write(JsonUtil.toJson(ResultVO.error(400, e.getMessage())));
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getRequestURI().substring(req.getContextPath().length());
        Long userId = (Long) req.getSession().getAttribute("userId");

        try {
            if (path.startsWith("/knowledge/")) {
                System.out.println("进来了1");
                Long id = Long.parseLong(path.substring("/knowledge/".length()));
                KnowledgeBaseDTO dto = JsonUtil.fromJson(IOUtils.toString(req.getReader()), KnowledgeBaseDTO.class);
                System.out.println("进来了2");
                KnowledgeBase updatedBase = knowledgeService.updateBase(id, dto, userId);
                resp.getWriter().write(JsonUtil.toJson(ResultVO.success(updatedBase)));
            } else {
                throw new IllegalArgumentException("Invalid request path");
            }
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write(JsonUtil.toJson(ResultVO.error(400, e.getMessage())));
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("delete");
        String path = req.getRequestURI().substring(req.getContextPath().length());
        Long userId = (Long) req.getSession().getAttribute("userId");

        try {
            if (path.startsWith("/knowledge/")) {
                Long id = Long.parseLong(path.substring("/knowledge/".length()));
                knowledgeService.deleteBase(id, userId);
                resp.getWriter().write(JsonUtil.toJson(ResultVO.success("Knowledge base deleted successfully")));
            } else {
                throw new IllegalArgumentException("Invalid request path");
            }
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write(JsonUtil.toJson(ResultVO.error(400, e.getMessage())));
        }
    }
}